package queue;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * 出款方
 * @author：涂有
 * @date 2017年2月18日 下午10:06:23
 */
public class QLender implements MessageListener{

	private QueueConnection connection;
	private QueueSession session;
	private Queue requestQueue;
	
	public QLender(String queueConnectionFactory, String requestQueue) throws NamingException, JMSException{
		
		Context context = new InitialContext();
		QueueConnectionFactory qcf = (QueueConnectionFactory)context.lookup(queueConnectionFactory);
		connection = qcf.createQueueConnection();
		connection.start();
		
		session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
		this.requestQueue = (Queue)context.lookup(requestQueue);
		
		QueueReceiver receiver = session.createReceiver(this.requestQueue);
		receiver.setMessageListener(this);
		System.out.println("正在等待申请中。。。");
	}
	
	@Override
	public void onMessage(Message arg0) {

		try {
			MapMessage mapMessage = (MapMessage) arg0;
			double salary = mapMessage.getDouble("Salary");
			double loanAmount = mapMessage.getDouble("LoanAmount");
			String response = null;
			if (salary > loanAmount) {

				response = "accept";
			} else {

				response = "decline";
			}
			response = "申请：" + salary + "," + loanAmount + ";" + response;
			System.out.println(response);
			TextMessage textMessage = session.createTextMessage(response);
			textMessage.setJMSCorrelationID(mapMessage.getJMSMessageID());
			QueueSender sender = session.createSender((Queue) mapMessage.getJMSReplyTo());
			sender.send(textMessage);
			System.out.println("正在等待申请中。。。");
		} catch (Exception e) {
		}
	}

	private void exit(){
		
		try {
			connection.close();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws NamingException, JMSException, IOException {
		
		QLender lender = new QLender("a", "b");
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Press enter to quit application");
		reader.readLine();
		lender.exit();
	}
}
